package org.wwy.sql;

import org.wwy.sql.config.ModuleConfig;

import java.io.File;
import java.io.FilenameFilter;
import java.util.*;

public class SqlMerger {

    private String basePath;

    private Map<String, ModuleConfig> configs = new LinkedHashMap<>();

    private Boolean isAll;


    private List<String> dialectTypes = Arrays.asList("oracle", "mysql", "inceptor");

    public void setBasePath(String basePath) {
        this.basePath = basePath;
    }

    public void merge(String module) {
        File file = new File(basePath);
        File file2 = getSubFile(file, module);
        ModuleConfig moduleConfig = null;
        if (configs.containsKey(module)) {
            moduleConfig = configs.get(module);
        }

        StringBuffer path = new StringBuffer("db");
        if (moduleConfig.isExistsDialectDir()) {
            String[] list = file.list((dir, name) -> dialectTypes.contains(name.toLowerCase()));
            if (list == null) {
                throw new RuntimeException("不存在方言目录!");
            }
            file2 = getSubFile(file2, list[0]);
        }
        File versionFolder = getSubFile(file2, moduleConfig.getVersion());
        File scriptFolder = versionFolder;
        if (isAll != null) {
            if (isAll) {
                scriptFolder = getSubFile(versionFolder, "all");
            } else {
                scriptFolder = getSubFile(versionFolder, "update");
            }
        }
        String[] sqlFiles = scriptFolder.list((dir, name) -> name.endsWith("sql"));
        if(sqlFiles != null){
            List<File> list = new ArrayList<>();
            List<Integer> nums = new ArrayList<>();
            for(String sqlFile : sqlFiles){
                String[] split = sqlFile.split(".");
                if(split.length < 3){
                    throw new RuntimeException("文件["+sqlFile+"]不符合规范!");
                }
                try {
                    Integer num = Integer.valueOf(split[0]);
                    nums.add(num);
                    if(nums.contains(num)){
                        throw new RuntimeException("文件["+sqlFile+"]存在重复序号!");
                    }
                    list.add(num,new File(sqlFile));
                }catch (Exception e){
                    throw new RuntimeException("文件["+sqlFile+"]第一位必须是数字!",e);
                }

            }

            for (File sqlFile : list) {
                System.out.println(sqlFile.getAbsoluteFile());
            }

        }
    }

    private File getSubFile(File file, String module) {
        String[] list = file.list((dir, name) -> module.equals(name));
        if (list == null) {
            throw new RuntimeException("文件夹[" + module + "]不存在!");
        }
        String filePath = list[0];
        return new File(filePath);
    }
}
